const express = require('express');
const path = require('path');
const mysql = require('mysql2/promise');
const app = express();

const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'tieba',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 初始化数据库
async function initDatabase() {
  try {
    const connection = await pool.getConnection();
    
    // 检查数据库是否存在
    await connection.query(`CREATE DATABASE IF NOT EXISTS tieba`);
    await connection.query(`USE tieba`);
    
    // 创建info表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS info (
        name VARCHAR(255) NOT NULL,
        content VARCHAR(255) NOT NULL
      )
    `);
    
    connection.release();
    console.log('数据库初始化成功');
  } catch (error) {
    console.error('数据库初始化失败:', error);
    process.exit(1); // 如果数据库初始化失败，则退出程序
  }
}

// 提供静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 处理表单数据
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// API端点，获取项目列表
app.get('/api/items', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM info');
    res.json(rows);
  } catch (error) {
    console.error('获取项目列表失败:', error);
    res.status(500).json({ success: false, message: '获取项目列表失败' });
  }
});

// 添加新项目
app.post('/api/items', async (req, res) => {
  try {
    const { name, content } = req.body;
    
    if (!name || !content) {
      return res.status(400).json({ success: false, message: 'name和content不能为空' });
    }
    
    const [result] = await pool.query(
      'INSERT INTO info (name, content) VALUES (?, ?)',
      [name, content]
    );
    
    res.json({ 
      success: true, 
      message: '添加成功',
      data: { name, content }
    });
  } catch (error) {
    console.error('添加项目失败:', error);
    res.status(500).json({ success: false, message: '添加项目失败' });
  }
});

// 删除项目
app.delete('/api/items/:id', async (req, res) => {
  try {
    const id = req.params.id;
    
    const [result] = await pool.query(
      'DELETE FROM info WHERE name = ?',
      [id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '项目不存在' });
    }
    
    res.json({ success: true, message: '删除成功' });
  } catch (error) {
    console.error('删除项目失败:', error);
    res.status(500).json({ success: false, message: '删除项目失败' });
  }
});

// 启动服务器前初始化数据库
initDatabase().then(() => {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
  });
});
